package cn.jbolt.core.base.config;

import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.RandomUtil;
import com.jfinal.kit.StrKit;

/**
 * JBolt分布式机房数据中心获取workId datacenterId配置工具类
 */
public class JBoltSnowFlakeIdConfig {
    /**
     * workId使用IP生成
     * @return workId
     */
    public static Long getWorkId() {
        String hostAddress = NetUtil.getLocalhost().getHostAddress();
        if(StrKit.isBlank(hostAddress)){
            // 失败就随机
            return RandomUtil.randomLong(0,31);
        }
        int[] ints = hostAddress.codePoints().toArray();
        int sums = 0;
        for (int b : ints) {
            sums = sums + b;
        }
        return (long) (sums % 32);
    }


    /**
     * dataCenterId使用hostName生成
     * @return dataCenterId
     */
    public static Long getDataCenterId() {
        String hostName = NetUtil.getLocalHostName();
        if(StrKit.isBlank(hostName)){
            // 失败就随机
            return RandomUtil.randomLong(0,31);
        }
        int[] ints = hostName.codePoints().toArray();
        int sums = 0;
        for (int i: ints) {
            sums = sums + i;
        }
        return (long) (sums % 32);
    }

}
